<template>
  <div class="allocation-page">
    <!-- 数据筛选 -->
    <el-card class="filter-card" shadow="never">
      <div class="filter-title">数据筛选</div>
      <el-form :inline="true" :model="filter" class="filter-form">
        <el-form-item label="调拨单号：">
          <el-input
            v-model="filter.AllocateId"
            placeholder="请输入/扫描单号"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="起始时间：">
          <el-date-picker
            v-model="filter.OrderCreatorTime"
            type="date"
            placeholder="起始时间"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="单据状态：">
          <el-select
            v-model="filter.State"
            placeholder="请选择"
            style="width: 120px"
          >
            <el-option
              v-for="opt in statusOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="ShowAllocation"
            ><el-icon> <Search /> </el-icon>查询</el-button
          >
          <el-button @click="handleReset"
            ><el-icon> <Refresh /> </el-icon>重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据列表操作栏 -->
    <el-card class="table-card" shadow="never">
      <div class="table-toolbar">
        <span class="table-title">数据列表</span>
        <div class="table-actions">
          <el-button type="primary" size="small" @click="openDialog">
            <el-icon><Plus /></el-icon>新增
          </el-button>
          <el-button size="small">
            <el-icon><Delete /></el-icon>删除
          </el-button>
          <el-button size="small">
            <el-icon><Download /></el-icon>导出
          </el-button>
        </div>
      </div>

      <!-- 统计卡片 -->
      <div class="statistics-cards" style="margin-bottom: 20px;">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number blue">{{ allocationCount }}</div>
                <div class="stat-label">调拨单数量</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number blue">{{ totalProductQuantity }}</div>
                <div class="stat-label">调拨货品数量</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number green">{{ (totalProductAmount || 0).toFixed(2) }}</div>
                <div class="stat-label">调拨产品金额</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" border style="width: 100%; margin-top: 10px">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="allocateId" label="调拨单号" width="100" />
        <el-table-column prop="productName" label="产品名称" width="160" />
        <el-table-column prop="productCode" label="产品编码" width="120" />
        <el-table-column prop="specifications" label="规格" width="70" />
                  <el-table-column prop="quantity" label="数量" width="60">
            <template #default="scope">
              {{ scope.row.quantity || 0 }}
            </template>
          </el-table-column>
        <el-table-column prop="depotName" label="原仓库" width="80" />
        <el-table-column prop="locationName" label="原库位" width="120" />
        <el-table-column
          prop="allocateWarehouse"
          label="调拨仓库"
          width="100"
        />
        <el-table-column prop="state" label="状态" width="100">
          <template #default="scope">
            <span v-if="scope.row.state === 0">等待审核</span>
            <span v-if="scope.row.state === 1">审核成功</span>
            <span v-if="scope.row.state === 2">审核失败</span>
          </template>
        </el-table-column>
        <el-table-column prop="auditor" label="审核人" width="80" />
        <el-table-column prop="auditTime" label="审核时间" width="120" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-link
              type="primary"
              @click="viewDialog(scope.row)"
              :underline="false"
              >查看</el-link
            >
            <el-link
              type="primary"
              @click="editDialog(scope.row)"
              :underline="false"
              style="margin-left: 8px"
              >编辑</el-link
            >
            <el-link
              type="primary"
              @click="DelProduct(scope.row)"
              :underline="false"
              style="margin-left: 8px"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作栏和分页 -->
      <div class="table-footer">
        <div class="batch-actions">
          <el-button size="small">全选</el-button>
          <el-button size="small">反选</el-button>
          <el-select size="small" placeholder="批量操作" style="width: 120px">
            <el-option label="批量删除" value="delete" />
            <el-option label="批量导出" value="export" />
          </el-select>
        </div>
        <div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="Total.PageIndex"
            v-model:page-size="Total.PageSize"
            :page-sizes="[15, 30, 45, 60]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="Total.totalCount"
          />
        </div>
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" title="新增调拨单" width="80%">
      <el-form :model="allocationForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="调拨单号">
              <el-input
                v-model="allocationForm.allocateId"
                placeholder="自动生成"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="调拨仓库" required>
              <el-input
                v-model="allocationForm.allocateWarehouse"
                placeholder="请选择人员/类型/类别"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联订单号">
              <el-input v-model="allocationForm.orderNumber" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="制单人">
              <el-input v-model="allocationForm.orderCreator" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单时间">
              <el-date-picker
                v-model="allocationForm.orderCreatorTime"
                type="date"
                placeholder="请选择日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input
            v-model="allocationForm.note"
            type="textarea"
            :rows="3"
            maxlength="300"
            show-word-limit
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <div style="margin: 20px 0 10px 0; font-weight: bold">产品信息</div>
      <div style="margin-bottom: 10px">
        <el-button type="primary" size="small" @click="fetchProducts"
          >新增产品</el-button
        >
      </div>
      <el-table :data="allocationProductForm" border>
        <el-table-column prop="id" label="产品ID" width="100">
          <template #default="scope">
            <div>
              <div
                v-if="scope.row.productId || scope.row.id"
                style="color: #409eff"
              >
                ID: {{ scope.row.productId || scope.row.id }}
              </div>
              <div v-else style="color: #f56c6c">缺失</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="productCode" label="产品编码" />
        <el-table-column prop="specifications" label="规格" />
        <el-table-column prop="price" label="单价" />
        <el-table-column label="数量">
          <template #default="scope">
            <el-input
              v-model.number="scope.row.quantity"
              type="number"
              min="0"
              style="width: 80px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="locationName" label="库位" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-link type="danger" @click="removeProductFromForm(scope.$index)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right; margin-top: 10px">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </div>
    </el-dialog>

    <!-- 产品选择弹框 -->
    <el-dialog
      v-model="productDialogVisible"
      title="选择产品"
      width="80%"
      :close-on-click-modal="false"
    >
      <el-table
        :data="productList"
        border
        style="width: 100%"
        @selection-change="(selection) => (selectedProducts = selection)"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="产品ID" width="80">
          <template #default="scope">
            <span v-if="scope.row.id" style="color: #409eff">
              {{ scope.row.id }}
            </span>
            <span v-else style="color: #f56c6c">缺失</span>
          </template>
        </el-table-column>
        <el-table-column prop="productCode" label="产品编码" width="120" />
        <el-table-column prop="productName" label="产品名称" width="160" />
        <el-table-column prop="specifications" label="规格" width="100" />
        <el-table-column prop="price" label="单价" width="100">
          <template #default="scope">
            ¥{{ scope.row.price || scope.row.unitPrice || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80">
          <template #default="scope">
            {{ scope.row.stock || scope.row.inventory || scope.row.stockQuantity || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="locationName" label="库位" width="120">
          <template #default="scope">
            {{ scope.row.locationName || scope.row.location || scope.row.warehouse || '默认库位' }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述">
          <template #default="scope">
            {{ scope.row.description || scope.row.desc || scope.row.remark || scope.row.note || '-' }}
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelSelectProducts">取消</el-button>
          <el-button
            type="primary"
            @click="confirmSelectProducts"
            :disabled="selectedProducts.length === 0"
          >
            确认选择 ({{ selectedProducts.length }})
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看弹框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="调拨单详情"
      width="90%"
      :close-on-click-modal="false"
    >
      <div class="view-dialog-content">
        <!-- 基本信息 -->
        <div class="info-section">
          <div class="info-row">
            <div class="info-item">
              <span class="info-label">调拨单号：</span>
              <span class="info-value">{{ viewData.allocateId || "-" }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">单据状态：</span>
              <span class="info-value">
                <span v-if="viewData.state === 0">等待审核</span>
                <span v-if="viewData.state === 1">审核成功</span>
                <span v-if="viewData.state === 2">审核失败</span>
              </span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <span class="info-label">关联单号：</span>
              <span class="info-value">{{ viewData.orderNumber || "-" }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">制单人：</span>
              <span class="info-value">{{ viewData.orderCreator || "-" }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">制单日期：</span>
              <span class="info-value">{{
                formatDate(viewData.orderCreatorTime) || "-"
              }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item full-width">
              <span class="info-label">备注：</span>
              <span class="info-value">{{ viewData.note || "无" }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item full-width">
              <span class="info-label">审核原因：</span>
              <span class="info-value">{{
                viewData.auditReason || "同意"
              }}</span>
            </div>
          </div>
        </div>

        <!-- 产品信息表格 -->
        <div class="product-section">
          <el-table :data="viewProductData" border style="width: 100%">
            <el-table-column
              prop="productCode"
              label="产品编码"
              width="100"
              align="center"
            />
            <el-table-column
              prop="productName"
              label="产品名称"
              width="160"
              align="center"
            />
            <el-table-column
              prop="specifications"
              label="规格"
              width="80"
              align="center"
            />
            <el-table-column
              prop="batch"
              label="批次"
              width="100"
              align="center"
            />
            <el-table-column
              prop="quantity"
              label="数量"
              width="80"
              align="center"
            />
            <el-table-column
              prop="currentLocation"
              label="当前库位"
              width="140"
              align="center"
            />
            <el-table-column
              prop="targetLocation"
              label="调拨仓库"
              width="140"
              align="center"
            />
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeViewDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElCard,
  ElLink,
  ElIcon,
  ElRow,
  ElCol,
  ElDialog,
  ElMessageBox,
  ElMessage,
} from "element-plus";
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Download,
} from "@element-plus/icons-vue";

import { allread, allwrite } from "@/systeamaxios/sysaxiosHelpers";
import axios from "axios";

// 创建产品API的axios实例
const productApi = axios.create({
  baseURL: "http://112.126.93.146:8000",
  timeout: 5000,
});
onMounted(() => {
  ShowAllocation();
});
const filter = ref({
  AllocateId: "",
  OrderCreatorTime: "",
  State: "",
});
const statusOptions = [
  { label: "请选择", value: "" },
  { label: "等待审核", value: "0" },
  { label: "审核成功", value: "1" },
  { label: "审核失败", value: "2" },
];
const Total = ref({
  PageSize: 15,
  PageIndex: 1,
  totalCount: 1,
  totalPage: 1,
});
// 定义调拨单数据项接口
interface AllocationTableItem {
  id?: string | number;
  allocateId?: string;
  productName?: string;
  productCode?: string;
  specifications?: string;
  quantity?: number | string;
  depotName?: string;
  locationName?: string;
  allocateWarehouse?: string;
  state?: number;
  auditor?: string;
  auditTime?: string;
  orderNumber?: string;
  orderCreator?: string;
  orderCreatorTime?: string;
  note?: string;
  auditReason?: string;
  [key: string]: any;
}

const tableData = ref<AllocationTableItem[]>([]);

// 统计数据
const allocationCount = ref(0)
const totalProductQuantity = ref(0)
const totalProductAmount = ref(0)
const ShowAllocation = async () => {
  try {
    const res = await allread.get("/lssueread/api/Allocate/GetAllocate", {
      params: {
        PageIndex: Total.value.PageIndex,
        PageSize: Total.value.PageSize,
        AllocateId: filter.value.AllocateId,
        OrderCreatorTime: filter.value.OrderCreatorTime,
        State: filter.value.State,
      },
    });
    
    console.log("主表格API返回的数据:", res.data);
    console.log("主表格数据项示例:", res.data.pageDatas?.[0]);
    tableData.value = res.data.pageDatas || [];
    Total.value.totalCount = res.data.totalCount || 0;
    Total.value.totalPage = res.data.totalPage || 0;
    
    // 计算统计数据
    await calculateStatistics();
      } catch (error) {
      console.error("获取调拨单数据失败:", error);
      ElMessage.error("获取调拨单数据失败");
    }
};

// 计算统计数据
const calculateStatistics = async () => {
  if (tableData.value && tableData.value.length > 0) {
    // 计算调拨单数量（去重）
    const uniqueAllocations = new Set(tableData.value.map((item: AllocationTableItem) => item.allocateId).filter(Boolean));
    allocationCount.value = uniqueAllocations.size;
    
    // 计算总调拨货品数量
    totalProductQuantity.value = tableData.value.reduce((sum: number, item: AllocationTableItem) => {
      return sum + (Number(item.quantity) || 0);
    }, 0);
    
    // 获取产品价格信息来计算总金额
    await calculateTotalAmount();
    
    console.log('统计计算结果:', {
      调拨单数量: allocationCount.value,
      调拨货品数量: totalProductQuantity.value,
      调拨产品金额: totalProductAmount.value
    });
  } else {
    allocationCount.value = 0;
    totalProductQuantity.value = 0;
    totalProductAmount.value = 0;
  }
};

// 计算总调拨产品金额
const calculateTotalAmount = async () => {
  try {
    // 获取所有产品编码
    const productCodes = [...new Set(tableData.value.map((item: AllocationTableItem) => item.productCode).filter(Boolean))];
    
    if (productCodes.length === 0) {
      totalProductAmount.value = 0;
      return;
    }
    
    // 调用产品API获取价格信息
    const response = await productApi.get("/basicread/api/Product/GetProduct");
    const products = response.data.data || response.data || [];
    
    // 创建产品价格映射
    const priceMap = new Map<string, number>();
    products.forEach((product: any) => {
      if (product.productCode && product.price) {
        priceMap.set(product.productCode, Number(product.price));
      }
    });
    
    // 计算总金额
    totalProductAmount.value = tableData.value.reduce((sum: number, item: AllocationTableItem) => {
      const price = priceMap.get(item.productCode || '') || 0;
      const quantity = Number(item.quantity) || 0;
      return sum + (price * quantity);
    }, 0);
    
    console.log('产品价格映射:', Object.fromEntries(priceMap));
    console.log('调拨单数据:', tableData.value.map((item: AllocationTableItem) => ({
      productCode: item.productCode,
      quantity: item.quantity,
      price: priceMap.get(item.productCode || '') || 0
    })));
    
  } catch (error) {
    console.error('获取产品价格失败:', error);
    // 如果获取价格失败，设置为0
    totalProductAmount.value = 0;
  }
};
const handleReset = () => {
  filter.value = { AllocateId: "", OrderCreatorTime: "", State: "" };
};
const DelProduct = (row: AllocationTableItem) => {
  console.log("删除调拨单，ID:", row.id);

  if (!row.id) {
    ElMessage.error("调拨单号不能为空");
    return;
  }

  ElMessageBox.confirm("此操作将永久删除该数据，是否继续？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      console.log("发送删除请求，调拨单号:", row.id);
      allwrite
        .get("/lssuewrite/api/Allocate/DelAllocate", {
          params: { Id: row.id },
        })
        .then((res) => {
          console.log("删除响应:", res.data);
          if (res.data.code == 200) {
            ElMessage.success(res.data.message);
            ShowAllocation();
          } else {
            ElMessage.warning(res.data.message);
          }
        })
        .catch((err) => {
          console.error("删除请求失败:", err);
          ElMessage.error("删除失败，请重试");
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 定义产品相关的类型接口
interface Product {
  id?: string | number;
  productCode?: string;
  code?: string;
  productName?: string;
  name?: string;
  specifications?: string;
  spec?: string;
  price?: number;
  unitPrice?: number;
  stock?: number;
  locationName?: string;
  description?: string;
  [key: string]: any;
}

interface AllocationProduct {
  productName: string;
  productCode: string;
  specifications: string;
  price: number;
  quantity: number | string;
  locationName: string;
  id?: string | number;
  productId?: string | number;
  [key: string]: any;
}

// 定义API需要的ProductItem接口
interface ProductItem {
  productId: number;
  quantity: number;
  productCode?: string; // 添加ProductCode字段
}

// 定义创建调拨单的请求接口
interface CreateAllocationRequest {
  allocateId: string;
  orderNumber: string;
  allocateWarehouse: string;
  products: ProductItem[];
  note?: string;
  orderCreator?: string;
  orderCreatorTime: string;
  state: number;
}

// 定义查看数据的类型接口
interface ViewData {
  allocateId?: string;
  state?: number;
  orderNumber?: string;
  orderCreator?: string;
  orderCreatorTime?: string;
  note?: string;
  auditReason?: string;
  [key: string]: any;
}

interface ViewProductData {
  productCode?: string;
  productName?: string;
  specifications?: string;
  batch?: string;
  quantity?: string;
  currentLocation?: string;
  targetLocation?: string;
  [key: string]: any;
}

const dialogVisible = ref(false);
const viewDialogVisible = ref(false);
const viewData = ref<ViewData>({});
const viewProductData = ref<ViewProductData[]>([]);

const allocationForm = ref({
  allocateId: "",
  orderNumber: "",
  allocateWarehouse: "",
  products: [
    {
      productCode: "",
      quantity: "",
    },
  ],
  note: "",
  orderCreator: "",
  orderCreatorTime: "2025-07-24T11:43:24.446Z",
  state: 0,
});
const openDialog = () => {
  // 生成当前时间的调拨单号（时分秒）
  const now = new Date();
  const pad = (n: number) => n.toString().padStart(2, "0");
  const allocateId =
    pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds());

  // 格式化当前时间为ISO字符串
  const currentTime = now.toISOString();

  allocationForm.value = {
    allocateId: allocateId,
    orderNumber: "",
    allocateWarehouse: "",
    products: [],
    note: "",
    orderCreator: "",
    orderCreatorTime: currentTime,
    state: 0,
  };
  allocationProductForm.value = [];
  dialogVisible.value = true;
};
const closeDialog = () => {
  dialogVisible.value = false;
};
// 新增：编辑弹窗方法
const editDialog = (row: AllocationTableItem) => {
  Object.assign(allocationForm.value, row);
  ShowAllocationProduct(row.allocateId || '');
  dialogVisible.value = true;
};
const allocationProductForm = ref<AllocationProduct[]>([]);
const ShowAllocationProduct = (allocateId: string) => {
  allread
    .get("/api/Allocate/GetAllocateProduct", {
      params: { AllocateId: allocateId },
    })
    .then((res) => {
      allocationProductForm.value = res.data.data || [];
    })
    .catch((error) => {
      console.error("获取调拨单产品数据失败:", error);
      ElMessage.error("获取调拨单产品数据失败");
    });
};

const submitForm = async () => {
  // 表单验证
  if (!allocationForm.value.allocateId) {
    ElMessage.error("调拨单号不能为空");
    return;
  }

  if (!allocationForm.value.orderNumber) {
    ElMessage.error("关联订单号不能为空");
    return;
  }

  if (!allocationForm.value.allocateWarehouse) {
    ElMessage.error("调拨仓库不能为空");
    return;
  }

  if (allocationProductForm.value.length === 0) {
    ElMessage.error("请至少添加一个产品");
    return;
  }

  // 验证产品数量和ID
  for (const product of allocationProductForm.value) {
    if (!product.quantity || Number(product.quantity) <= 0) {
      ElMessage.error(`产品 ${product.productName} 的数量必须大于0`);
      return;
    }
    const actualProductId = product.productId || product.id;
    if (!actualProductId) {
      console.error("产品缺少ID详情:", product);
      ElMessage.error(
        `产品 ${product.productName} 缺少产品ID，请重新选择该产品`
      );
      return;
    }

    // 验证产品ID是否为有效数字
    const productId = Number(actualProductId);
    if (isNaN(productId) || productId <= 0) {
      console.error("产品ID无效:", actualProductId, "产品:", product);
      ElMessage.error(
        `产品 ${product.productName} 的产品ID无效 (${actualProductId})，请重新选择该产品`
      );
      return;
    }

    // 验证产品编码是否存在且不为空
    if (!product.productCode || product.productCode.trim() === "") {
      console.error("产品缺少编码或编码为空:", product);
      ElMessage.error(
        `产品 ${product.productName} 缺少有效的产品编码，请重新选择该产品`
      );
      return;
    }
  }

  // 构造请求数据
  const requestData: CreateAllocationRequest = {
    allocateId: allocationForm.value.allocateId,
    orderNumber: allocationForm.value.orderNumber,
    allocateWarehouse: allocationForm.value.allocateWarehouse,
    products: allocationProductForm.value.map((item) => ({
      productId: Number(item.productId || item.id) || 0,
      quantity: Number(item.quantity) || 0,
      productCode: item.productCode || "", // 添加ProductCode字段
    })),
    note: allocationForm.value.note || "",
    orderCreator: allocationForm.value.orderCreator || "",
    orderCreatorTime:
      allocationForm.value.orderCreatorTime || new Date().toISOString(),
    state: 0,
  };

  try {
    console.log("提交调拨单数据:", requestData);
    console.log("产品列表详情:", allocationProductForm.value);

    // 详细检查每个产品的数据
    requestData.products.forEach((product, index) => {
      console.log(`产品 ${index + 1} 详细信息:`, {
        productId: product.productId,
        productCode: product.productCode,
        quantity: product.quantity,
        原始产品数据: allocationProductForm.value[index],
      });

      if (!product.productCode) {
        console.warn(`警告: 产品 ${index + 1} 的 productCode 为空`);
      }
      if (!product.productId || product.productId <= 0) {
        console.warn(
          `警告: 产品 ${index + 1} 的 productId 无效: ${product.productId}`
        );
      }
    });

    // 调用创建调拨单API
    const response = await allwrite.post(
      "/api/Allocate/CreateAllocate",
      requestData
    );

    console.log("创建调拨单响应:", response.data);

    if (response.data.code === 200 || response.data.success) {
      ElMessage.success("调拨单创建成功");
      closeDialog();
      ShowAllocation(); // 刷新列表
    } else {
      ElMessage.error(response.data.message || "创建调拨单失败");
    }
  } catch (error: any) {
    console.error("创建调拨单失败:", error);

    // 详细的错误处理
    if (error.response) {
      // 服务器响应了错误状态码
      const status = error.response.status;
      const message = error.response.data?.message || error.response.statusText;

      if (status === 404) {
        ElMessage.error(`API接口不存在 (404): /api/Allocate/CreateAllocate`);
        console.error("404错误详情:", {
          url: error.config?.url,
          baseURL: error.config?.baseURL,
          fullURL: `${error.config?.baseURL}${error.config?.url}`,
        });
      } else if (status === 405) {
        ElMessage.error(`HTTP方法不被允许 (405): 服务器不接受POST请求`);
        console.error("405错误详情:", {
          url: error.config?.url,
          method: error.config?.method,
          allowedMethods: error.response?.headers?.allow,
        });
      } else if (status === 500) {
        ElMessage.error(`服务器内部错误 (500): ${message}`);
      } else {
        ElMessage.error(`请求失败 (${status}): ${message}`);
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      ElMessage.error("无法连接到服务器，请检查网络连接和服务器状态");
      console.error("网络错误:", error.request);
    } else {
      // 其他错误
      ElMessage.error(`创建调拨单失败: ${error.message}`);
    }
  }
};
// 产品选择弹框相关状态
const productDialogVisible = ref(false);
const productList = ref<Product[]>([]);
const selectedProducts = ref<Product[]>([]);

// 新增产品时调用接口获取产品数据
const fetchProducts = async () => {
  try {
    const response = await productApi.get("/basicread/api/Product/GetProduct");
    console.log("产品API返回数据:", response.data);

    let products: any[] = [];
    if (response.data && Array.isArray(response.data)) {
      products = response.data;
    } else if (response.data.data && Array.isArray(response.data.data)) {
      products = response.data.data;
    } else {
      productList.value = [];
      ElMessage.warning("产品数据格式异常");
      return;
    }

    // 处理产品数据，确保每个产品都有ID
    productList.value = products.map((product: any, index: number) => {
      // 尝试多种可能的ID字段，优先使用productId
      const productId =
        product.productId ||
        product.id ||
        product.Id ||
        product.ProductId ||
        index + 1;

      console.log(`产品 ${product.productName || product.name} 的ID处理:`, {
        原始数据: product,
        所有字段: Object.keys(product),
        productId字段: product.productId,
        id字段: product.id,
        Id字段: product.Id,
        ProductId字段: product.ProductId,
        最终使用ID: productId,
        ID是否有效: productId && productId !== index + 1,
      });

      return {
        ...product,
        id: productId, // 统一使用id字段存储
        productId: productId, // 同时保留productId字段
        // 补充可能缺失的字段
        productCode: product.productCode || product.code || `CODE${productId}`,
        productName: product.productName || product.name || `产品${productId}`,
        specifications: product.specifications || product.spec || product.unit || '个',
        price: product.price || product.unitPrice || 0,
        stock: product.stock || product.inventory || product.stockQuantity || 0,
        locationName: product.locationName || product.location || product.warehouse || '默认库位',
        description: product.description || product.desc || product.remark || product.note || '暂无描述'
      };
    });

    console.log("处理后的产品列表:", productList.value);
    productDialogVisible.value = true;
  } catch (error: any) {
    console.error("获取产品数据失败:", error);

    if (error.response) {
      const status = error.response.status;
      if (status === 404) {
        ElMessage.error("产品API接口不存在，请检查服务器配置");
      } else {
        ElMessage.error(
          `获取产品数据失败 (${status}): ${
            error.response.data?.message || error.response.statusText
          }`
        );
      }
    } else if (error.request) {
      ElMessage.error(
        "无法连接到产品服务器 (localhost:5011)，请检查服务器状态"
      );
    } else {
      ElMessage.error(`获取产品数据失败: ${error.message}`);
    }
  }
};

// 验证产品ID是否有效
const validateProductId = (product: Product) => {
  const productName = product.productName || product.name || "未知产品";

  // 检查是否有任何形式的ID
  const hasAnyId =
    product.id || product.productId || product.Id || product.ProductId;

  if (!hasAnyId) {
    console.error("产品完全缺少ID字段:", {
      产品名称: productName,
      原始数据: product,
      所有字段: Object.keys(product),
    });
    return false;
  }

  // 检查ID是否为有效值（不是临时分配的索引ID）
  const actualId =
    product.productId || product.id || product.Id || product.ProductId;
  if (!actualId || Number(actualId) <= 0) {
    console.error("产品ID无效:", {
      产品名称: productName,
      ID值: actualId,
      原始数据: product,
    });
    return false;
  }

  return true;
};

// 确认选择产品
const confirmSelectProducts = () => {
  const addedCount = selectedProducts.value.length;
  let actualAddedCount = 0;
  let invalidProducts: string[] = [];

  selectedProducts.value.forEach((product: Product) => {
    const productName = product.productName || product.name || "未知产品";

    // 验证产品ID
    if (!validateProductId(product)) {
      invalidProducts.push(productName);
      return;
    }

    // 检查是否已存在相同产品
    const exists = allocationProductForm.value.find(
      (item) =>
        item.productCode === (product.productCode || product.code) ||
        item.id === product.id
    );

    if (!exists) {
      const newProduct: AllocationProduct = {
        productName: product.productName || product.name || `产品${product.id}`,
        productCode: product.productCode || product.code || `CODE${product.id}`,
        specifications: product.specifications || product.spec || product.unit || "个",
        price: product.price || product.unitPrice || 0,
        quantity: 1,
        locationName: product.locationName || product.location || product.warehouse || "默认库位",
        id: product.id, // 前端显示用的ID
        productId: product.productId || product.id, // 后端API需要的productId
      };

      console.log("添加产品到调拨单:", newProduct);
      console.log("原始产品数据:", product);

      // 验证关键字段
      if (!newProduct.productCode || newProduct.productCode.trim() === "") {
        console.error("警告: 添加的产品缺少有效的productCode", {
          产品名称: newProduct.productName,
          原始productCode: product.productCode,
          原始code: product.code,
          最终productCode: newProduct.productCode,
        });
      }

      allocationProductForm.value.push(newProduct);
      actualAddedCount++;
    } else {
      console.log("产品已存在，跳过:", product.productName || product.name);
    }
  });

  selectedProducts.value = [];
  productDialogVisible.value = false;

  // 提供详细的反馈信息
  if (invalidProducts.length > 0) {
    ElMessage.error(
      `以下产品缺少有效的产品ID，无法添加：${invalidProducts.join(", ")}`
    );
    console.error("无效产品列表:", invalidProducts);
  }

  if (actualAddedCount > 0) {
    ElMessage.success(`已成功添加 ${actualAddedCount} 个产品`);
  } else if (addedCount > 0 && invalidProducts.length === 0) {
    ElMessage.warning("所选产品已存在，未添加新产品");
  } else if (addedCount === 0) {
    ElMessage.warning("未选择任何产品");
  }
};

// 取消选择产品
const cancelSelectProducts = () => {
  selectedProducts.value = [];
  productDialogVisible.value = false;
};

// 从调拨单中移除产品
const removeProductFromForm = (index: number) => {
  ElMessageBox.confirm("确定要删除这个产品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      allocationProductForm.value.splice(index, 1);
      ElMessage.success("产品已删除");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 查看弹框方法
const viewDialog = (row: AllocationTableItem) => {
  console.log("查看弹框接收到的行数据:", row);
  viewData.value = {
    ...row,
    // 确保所有需要的字段都有默认值
    allocateId: row.allocateId || "-",
    state: row.state !== undefined ? row.state : 0,
    orderNumber: row.orderNumber || "-",
    orderCreator: row.orderCreator || row.auditor || "-", // 如果没有制单人，使用审核人
    orderCreatorTime: row.orderCreatorTime || row.auditTime || "-",
    note: row.note || "无",
    auditReason: row.auditReason || "同意",
  };

  // 保存主表格行数据，用于补充API中缺失的字段
  const mainTableRowData = row;

  ShowAllocationProductForView(row.allocateId || '', mainTableRowData);
  viewDialogVisible.value = true;
};

// 关闭查看弹框
const closeViewDialog = () => {
  viewDialogVisible.value = false;
  viewData.value = {};
  viewProductData.value = [];
};

// 获取查看弹框的产品数据
const ShowAllocationProductForView = (
  allocateId: string,
  mainTableRowData?: AllocationTableItem
) => {
  allread
    .get("/api/Allocate/GetAllocateProduct", {
      params: { AllocateId: allocateId },
    })
    .then((res) => {
      // 使用API返回的真实数据并映射字段
      console.log("API返回的产品数据:", res.data);
      const rawData = res.data.data || [];

      // 将API数据映射到查看弹框需要的字段格式
      console.log("原始数据项示例:", rawData[0]);

      viewProductData.value = rawData.map((item: any) => {
        const mappedItem: ViewProductData = {
          productCode: item.productCode || "-",
          productName: item.productName || "-",
          specifications: item.specifications || "个",
          batch: item.batch || "20156852",
          // 如果API数据中没有quantity，使用主表格数据
          quantity:
            item.quantity ||
            (mainTableRowData ? mainTableRowData.quantity?.toString() : "-"),
          currentLocation: item.locationName || item.depotName || "报损库位",
          // 如果API数据中没有allocateWarehouse，使用主表格数据
          targetLocation:
            item.allocateWarehouse ||
            (mainTableRowData ? mainTableRowData.allocateWarehouse : "-"),
        };
        console.log(
          "API数据字段检查 - quantity:",
          item.quantity,
          "allocateWarehouse:",
          item.allocateWarehouse
        );
        console.log(
          "主表格数据补充 - quantity:",
          mainTableRowData?.quantity,
          "allocateWarehouse:",
          mainTableRowData?.allocateWarehouse
        );
        console.log("最终映射后的数据项:", mappedItem);
        return mappedItem;
      });
    })
    .catch((err) => {
      console.error("获取产品数据失败:", err);
      ElMessage.warning("获取详细产品数据失败，显示基本信息");

      // 如果API调用失败，使用主表格数据创建备用数据
      if (mainTableRowData) {
        const fallbackData: ViewProductData[] = [
          {
            productCode: mainTableRowData.productCode || "-",
            productName: mainTableRowData.productName || "-",
            specifications: mainTableRowData.specifications || "个",
            batch: "20156852",
            quantity: mainTableRowData.quantity?.toString() || "-",
            currentLocation:
              mainTableRowData.locationName ||
              mainTableRowData.depotName ||
              "报损库位",
            targetLocation: mainTableRowData.allocateWarehouse || "-",
          },
        ];
        console.log("API失败，使用主表格备用数据:", fallbackData);
        viewProductData.value = fallbackData;
      }
    });
};

// 格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return "-";
  try {
    const date = new Date(dateString);
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch (error) {
    return dateString;
  }
};




 
</script>




<style scoped>









.allocation-page {
  background: #f5f6fa;
  min-height: 100vh;
  padding: 20px;
}

.filter-card {
  margin-bottom: 18px;
}

.filter-title {
  font-weight: bold;
  font-size: 15px;
  margin-bottom: 8px;
}

.filter-form {
  margin-top: 8px;
}

.table-card {
  padding-bottom: 0;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0;
}

.table-title {
  font-weight: bold;
  font-size: 15px;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.table-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.el-table th,
.el-table td {
  text-align: center;
}

/* 查看弹框样式 */
.view-dialog-content {
  padding: 0;
}

.info-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.info-row {
  display: flex;
  margin-bottom: 15px;
  align-items: center;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-item {
  flex: 1;
  display: flex;
  align-items: center;
  margin-right: 30px;
}

.info-item:last-child {
  margin-right: 0;
}

.info-item.full-width {
  flex: 1;
  margin-right: 0;
}

.info-label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
  margin-right: 10px;
}

.info-value {
  color: #303133;
  word-break: break-all;
}

.product-section {
  margin-top: 10px;
}

.dialog-footer {
  text-align: center;
}

/* 统计卡片样式 */
.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-content {
  padding: 10px;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-number.blue {
  color: #409eff;
}

.stat-number.green {
  color: #67c23a;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

/* 弹框表格样式 */
:deep(.el-dialog .el-table) {
  font-size: 14px;
}

:deep(.el-dialog .el-table th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.el-dialog .el-table td) {
  padding: 8px 0;
}
</style>
